<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>产品管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-row>
      <el-col :span="24">
        <el-button
          type="primary"
          icon="el-icon-edit"
          @click="dialogFormVisible = true"
          >新增</el-button
        >
        <el-button type="danger" icon="el-icon-delete" @click="batchDelete"
          >批量删除</el-button
        >

        <!-- 新增按钮弹出框 -->
        <el-dialog title="添加产品" :visible.sync="dialogFormVisible">
          <el-form :model="form">
            <el-form-item label="产品名称" label-width="120px">
              <el-input v-model="form.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="产品价格" label-width="120px">
              <el-input v-model="form.price" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="产品分类" label-width="120px">
              <el-cascader
                :options="options"
                clearable
                v-model="sort"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="产品库存" label-width="120px">
              <el-input v-model="form.stock" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="产品描述" label-width="120px">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
                v-model="form.desc"
              ></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="addProduct">确 定</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>

    <!-- 表格区域 -->
    <el-table
      :data="ProductData"
      height="400"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
      row-class-name="tableRowClassName"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column prop="id" label="编号" width="50"></el-table-column>
      <el-table-column prop="img" label="图片">
        <template slot-scope="scope">
          <el-image
            style="width: 50px; height: 50px"
            :src="require('../assets/img/' + scope.row.img)"
            fit="contain"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="产品名称"></el-table-column>
      <el-table-column prop="level1" label="一级分类"></el-table-column>
      <el-table-column prop="level2" label="二级分类"></el-table-column>
      <el-table-column prop="level3" label="三级分类"></el-table-column>
      <el-table-column prop="price" label="价格"></el-table-column>
      <el-table-column prop="stock" label="库存"></el-table-column>
      <el-table-column prop="desc" label="描述"></el-table-column>
      <el-table-column fixed="right" label="操作" width="180">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row.id)"
            >删除</el-button
          >
          <!-- 编辑按钮弹出框 -->
          <el-drawer
            title="编辑产品信息"
            :before-close="handleClose"
            :visible.sync="dialog"
            direction="rtl"
            custom-class="demo-drawer"
            ref="drawer"
            :modal="modalBool"
          >
            <div class="demo-drawer__content">
              <el-form :model="form">
                <el-form-item label="产品名称" label-width="120px">
                  <el-input v-model="form.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="产品价格" label-width="120px">
                  <el-input v-model="form.price" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="产品分类" label-width="120px">
                  <el-cascader
                    :options="options"
                    clearable
                    v-model="sort"
                  ></el-cascader>
                </el-form-item>
                <el-form-item label="产品库存" label-width="120px">
                  <el-input v-model="form.stock" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="产品描述" label-width="120px">
                  <el-input
                    type="textarea"
                    :rows="2"
                    placeholder="请输入内容"
                    v-model="form.desc"
                  ></el-input>
                </el-form-item>
              </el-form>
              <div class="demo-drawer__footer cancel">
                <el-button @click="cancelForm">取 消</el-button>
                <el-button
                  type="primary"
                  @click="editAddress"
                  :loading="loading"
                  >{{ loading ? "提交中 ..." : "确 定" }}</el-button
                >
              </div>
            </div>
          </el-drawer>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageParam.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="22"
      >
      </el-pagination>
    </div>
  </div>
</template>


<script>
// js样式
export default {
  data() {
    return {
      //级联选项
      options: [],
      sort: [],
      table: false,
      dialog: false,
      loading: false,
      modalBool: false,
      ProductData: [],
      multipleSelection: [],
      dialogFormVisible: false,
      form: {
        id: 0,
        name: "",
        price: "",
        stock: "",
        desc: "",
        level1: "",
        level2: "",
        level3: "",
        img: "",
      },

      pageParam: {
        pageNumber: 1,
        pageSize: 10,
      },
      formLabelWidth: "120px",
      timer: null,
    };
  },
  methods: {
    //新增产品的方法
    addProduct() {
      this.form.img = "tv01.jpg";
      this.form.level1 = this.sort[0];
      this.form.level2 = this.sort[1];
      if (this.sort[2]) {
        this.form.level3 = this.sort[2];
      } else {
        this.form.level3 = 0;
      }

      //提交数据
      if (this.form.name.length > 0 && this.form.price.length > 0) {
        this.$axios.post("/product", this.form).then((res) => {
          //重新加载页面
          if (res.status == 201) {
            this.$message({
              message: "添加成功",
              type: "success",
            });
            this.loadData();
            this.emptyForm();
          } else {
            this.$message.error("数据出错，请重新加载");
          }
        });
      }
      this.dialogFormVisible = false;
    },

    //清空表格
    emptyForm() {
      this.form.id = 0;
      this.form.name = "";
      this.form.price = "";
      this.form.stock = "";
      this.form.desc = "";
      this.form.level1 = "";
      this.form.level2 = "";
      this.form.level3 = "";
      this.form.img = "";
      this.sort = [];
    },

    //页面加载数据
    loadData: function () {
      this.$axios
        .get(
          "http://localhost:3000/product?_page=" +
            this.pageParam.pageNumber +
            "&_limit=" +
            this.pageParam.pageSize
        )
        .then((res) => {
          this.ProductData = res.data;
        });
      this.fenloadData();
    },

    //将分类选项的数字转换成对应的名称并显示在页面上
    fenloadData() {
      this.$axios.get("/proCategory").then((res) => {
        var dataArray = res.data;
        // 遍历得到的产品数据
        for (let i = 0; i < this.ProductData.length; i++) {
          for (let j = 0; j < dataArray.length; j++) {
            //当ProductData的level1等于分类数据第一层的id时，将对应的名称赋值给level1
            if (this.ProductData[i].level1 == dataArray[j].id) {
              this.ProductData[i].level1 = dataArray[j].name;
              let Alevel2 = dataArray[j].level2;
              // 当ProductData的level2等于分类数据第二层的id时，将对应的名称赋值给level2
              for (let z = 0; z < Alevel2.length; z++) {
                if (this.ProductData[i].level2 == Alevel2[z].id) {
                  this.ProductData[i].level2 = Alevel2[z].name;
                  let Alevel3 = Alevel2[z].level3;
                  // 当ProductData的level3等于分类数据第三层的id时，将对应的名称赋值给level3
                  if (Alevel3.length > 0) {
                    for (let x = 0; x < Alevel3.length; x++) {
                      if (this.ProductData[i].level3 == Alevel3[x].id) {
                        this.ProductData[i].level3 = Alevel3[x].name;
                      }
                    }
                  }
                }
              }
            }
          }
        }
      });
    },
    //新增按钮中的级联选择器的选项获取
    optionsData() {
      this.$axios.get("/proCategory").then((res) => {
        var optionsData = res.data;

        for (let i = 0; i < optionsData.length; i++) {
          var level1 = {};
          var level1Value = optionsData[i].id;
          var level1Label = optionsData[i].name;
          var level1children = optionsData[i].level2;

          level1.value = level1Value;
          level1.label = level1Label;
          var level = [];
          for (var j = 0; j < level1children.length; j++) {
            var level2 = {};
            var level2Value = level1children[j].id;
            var level2Label = level1children[j].name;
            var level2Children = level1children[j].level3;

            if (level2Children.length > 0) {
              level2.value = level2Value;
              level2.label = level2Label;
              var level3Children = [];
              for (let z = 0; z < level2Children.length; z++) {
                var level3 = {};
                var level3Value = level2Children[z].id;
                var level3Label = level2Children[z].name;
                level3.value = level3Value;
                level3.label = level3Label;
                level3Children.push(level3);
              }
              level2.children = level3Children;
              level.push(level2);
            } else {
              level2.value = level2Value;
              level2.label = level2Label;
              level.push(level2);
            }
          }
          level1.children = level;

          this.options.push(level1);
        }
      });
    },

    //表格全选复选按钮的方法
    handleSelectionChange(val) {
      this.multipleSelection = val.map((item) => {
        return item.id;
      });
    },

    //关闭编辑弹出框的方法
    handleClose(done) {
      if (this.loading) {
        return;
      }
      this.$confirm("确定要提交表单吗？")
        .then((_) => {
          this.loading = true;
          this.timer = setTimeout(() => {
            done();
            // 动画关闭需要一定的时间
            setTimeout(() => {
              this.loading = false;
            }, 400);
          }, 2000);
        })
        .catch((_) => {});
    },
    //取消编辑并关闭弹出框
    cancelForm() {
      this.loading = false;
      this.dialog = false;
      clearTimeout(this.timer);
      this.emptyForm();
    },
    //打开编辑，附上当项产品信息方法
    handleEdit(row) {
      this.dialog = true;
      for (var i = 0; i < this.options.length; i++) {
        if (this.options[i].label == row.level1) {
          this.form.level1 = this.options[i].value;
          this.sort[0] = this.options[i].value;
        }
      }
      const level2 = this.options.map((two) => {
        return two.children;
      });

      for (var j = 0; j < level2.length; j++) {
        for (var z = 0; z < level2[j].length; z++) {
          if (level2[j][z].label == row.level2) {
            this.form.level2 = level2[j][z].value;
            this.sort[1] = level2[j][z].value;
            if (level2[j][z].children) {
              for (let x = 0; x < level2[j][z].children.length; x++) {
                if (level2[j][z].children[x].label == row.level3) {
                  this.form.level3 = level2[j][z].children[x].value;
                  this.sort[2] = level2[j][z].children[x].value;
                }
              }
            } else {
              this.form.level3 = 0;
            }
          }
        }
      }

      this.form.id = row.id;
      this.form.name = row.name;
      this.form.price = row.price;
      this.form.stock = row.stock;
      this.form.desc = row.desc;
      this.form.img = row.img;
    },
    //编辑后提交新数据
    editAddress() {
      this.form.level1 = this.sort[0];
      this.form.level2 = this.sort[1];
      this.form.level3 = this.sort[2];

      this.$axios.put("/product/" + this.form.id, this.form).then((res) => {
        if (res.status == 200) {
          this.$message({
            type: "success",
            message: "修改成功!",
          });
          this.dialog = false;
          this.loadData();
          this.emptyForm();
        }
      });
    },
    //删除按钮方法
    handleDelete(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios.delete("/product/" + id).then((res) => {
            if (res.status == 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            }
            this.loadData();
          });
        })
        .catch(() => {});
    },
    //批量删除的方法
    batchDelete() {
      if (this.multipleSelection.length > 0) {
        this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            for (let i = 0; i < this.multipleSelection.length; i++) {
              let selId = this.multipleSelection[i];
              this.$axios.delete("/product/" + selId).then((res) => {
                this.loadData();
              });
            }
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          })
          .catch(() => {});
      } else {
        this.$message({
          message: "未选择任何产品！",
          type: "warning",
        });
      }
    },
    //分页方法
    //每页数据量发生变化时触发的事件
    handleSizeChange(pageSize) {
      this.pageParam.pageSize = pageSize;
      this.loadData();
    },
    //当前数据分页组件页码发生变化时触发的事件
    handleCurrentChange(val) {
      this.pageParam.pageNumber = val;
      this.loadData();
    },
  },
  mounted: function () {
    this.loadData();
    this.optionsData();
  },
};
</script>


  <style>
/* CSS样式 */
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
.el-row {
  margin-top: 20px;
  margin-bottom: 20px;
}

.el-col {
  border-radius: 4px;
}
.cancel {
  margin-left: 250px;
}
</style>